package com.earogya.logic.medical_records;

import java.util.Calendar;

import org.apache.struts.ehr.medical_records.model.AdmitPatient;
import org.apache.struts.ehr.medical_records.model.Guardian;
import org.apache.struts.ehr.medical_records.model.Address;
import org.apache.struts.ehr.medical_records.model.MergePatientLog;

import com.earogya.Constants;

import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.model.DataTypeException;
import ca.uhn.hl7v2.model.v251.datatype.ST;
import ca.uhn.hl7v2.model.v251.message.ADT_A30;

/***
 * Creates ADT A34 message to merge two patients
 * using MergePatientLog object.
 * @author Chamendri
 *
 */
public class CreateADT34 {

	private ADT_A30 adt;
	private MergePatientLog log;
	
	/**
	 * Accepts MergePatientLog object.
	 * @param log
	 */
	public CreateADT34(MergePatientLog log){
		this.adt=new ADT_A30();
		this.log=log;
	}
	
	/***
	 * Creates the ADT A34 message.
	 * @param sendingFacility
	 * @return the ADT A34 message.
	 * @throws HL7Exception
	 */
	public String createMessage(String sendingFacility) throws HL7Exception{
		this.addMessageHeader(sendingFacility);
		this.addMergeInformation();
		return adt.getMessage().encode();
	}
	
	/**
	 * Add MSH segment to ADT A34 message.
	 * @param sendingFacility
	 * @throws DataTypeException
	 */
	private void addMessageHeader(String sendingFacility) throws DataTypeException{
		adt.getMSH().getFieldSeparator().setValue("|");
		adt.getMSH().getEncodingCharacters().setValue("^~\\&");
		adt.getMSH().getDateTimeOfMessage().getTime().setValue(Calendar.getInstance().getTime());
		adt.getMSH().getMessageType().getMsg1_MessageCode().setValue("ADT");
		adt.getMSH().getMessageType().getTriggerEvent().setValue("A34");
		adt.getMSH().getSendingApplication().getUniversalID().setValue(Constants.SENDING_APPLICATION);
		adt.getMSH().getVersionID().getVersionID().setValue(Constants.HL7_VERSION);
		adt.getMSH().getSendingFacility().getUniversalID().setValue(sendingFacility);
		adt.getMSH().getReceivingApplication().getUniversalID().setValue(Constants.RECEIVING_APPLICATION_PATIENT_VISIT_SERVICE);
		adt.getMSH().getReceivingFacility().getUniversalID().setValue(sendingFacility);
	}
	
	/**
	 * Add MRG, PID and EVN segments.
	 * @throws DataTypeException
	 */
	private void addMergeInformation() throws DataTypeException{
		adt.getMRG().getPriorPatientID().getIDNumber().setValue(String.valueOf(log.getCurrent_patient_id()));
		adt.getPID().getPatientID().getIDNumber().setValue(String.valueOf(log.getNew_patient_id()));
		adt.getMSH().getDateTimeOfMessage().getTime().setValue(log.getMerge_date());
		adt.getEVN().getOperatorID(0).getIDNumber().setValue(String.valueOf(log.getMerging_person_id()));
	}

}
